var moduleIddata= getQueryString('moduleId');//专题id
var mbId= getQueryString('mbId');//模板id
var seavedata=[];//保存传给后台的值
var seavedatatone=[];// 第一组 保存传给后台的值
var seavedatatwo=[];// 第二组 保存传给后台的值
var pos =  getQueryString('pos');//在添加模板页 添加的模板的位置顺序
var moduleIddata= getQueryString('moduleId');//模板id
var widthheight={'picWidth':'','picHeight':''};
var width = '';
var height = '';
var spcialLinkConfitinit ='';
var modelIdeveyList=[];
var modelIdevey = {'typeId':1,'id':''};//需要传给 商品下载集合
var index =  parent.layer.getFrameIndex(window.name); 
var updateModeId = '';//编辑进来的 点击保存要添加的入参
var bwidthheight={'picWidth':'','picHeight':''};
// 多个落地页及图片传值[{},{},{}]
var params1 = {
                "subId":moduleIddata,//专题页id   moduleIddata  暂时t环境好使
                "modelUrl":'',//图片链接
                "modelType":'2',//模板类型(1.1张图2.2张图3.3张图纵向4.3张图横向5.单品详情6.商品集合)
                "contentIndex":'1',//图片排序
                "modelStatus":'',//模板状态(是否展示):展示0:不展示1
                "modelSpace":'',//模板间隔1:间隔0:不间隔
                "placeType":'',//插入链接类型(插入链接类型 1:专题页 2.分类页 3.品牌页 4.单品详情页 5.自定义url 6.商品集合 7.优惠券 8.无跳转)
                "placeContent":'',//链接内容 落地页值
                "userName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
}
seavedatatone.push(params1)
var params2 = {
                "subId":moduleIddata,//专题页id   moduleIddata  暂时t环境好使
                "modelUrl":'',//图片链接
                "modelType":'2',//模板类型(1.1张图2.2张图3.3张图纵向4.3张图横向5.单品详情6.商品集合)
                "contentIndex":'2',//图片排序
                "modelStatus":'',//模板状态(是否展示):展示0:不展示1
                "modelSpace":'',//模板间隔1:间隔0:不间隔
                "placeType":'',//插入链接类型(插入链接类型 1:专题页 2.分类页 3.品牌页 4.单品详情页 5.自定义url 6.商品集合 7.优惠券 8.无跳转)
                "placeContent":'',//链接内容 落地页值
                "userName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
}
seavedatatwo.push(params2)
//如果有moduleIddata 就调单类型模板详情查询 接口做回显
initdata (mbId)
var imghtml='';
function initdata (mbId){
    if(mbId){
        $(".change").html('模块编辑')
        web.doAjax(root.special.searchModelMsg, 'post', {'modelArrayId':mbId,'subId':moduleIddata}, succCallBack)
    }
}
function succCallBack(data){
    if(data.errorCode == 0){
        //页面回显
        if(data.data != null && data.data.length >0){
         $.each(data.data,function (i,ite) {
             //图片渲染
             imghtml += '  <li><img src="'+$(ite)[0].modelUrl+'"></li>'
                 $(".radionamebox").find('input').each(function(j,item){
                         if($(item).val() ==$(ite)[0].modelStatus){
                             $(item).attr('checked','checked')  
                         }
                     })
                     $(".radioretivalbox").find('input').each(function(j,item){
                         if($(item).val() == $(ite)[0].modelSpace){
                             $(item).attr('checked','checked')  
                         }
                     })
         widthinit($(ite),i);
        if(i == 0){
            $(".specialLink").attr('dataId',$(ite)[0].modelId);
        }else{
            $(".specialLinktwo").attr('dataId',$(ite)[0].modelId);
        }
         })
         $(".img").html(imghtml)
         spcialLinkConfit.specialDefaultInit() 
        }
     }else{
        $.Huimodalalert('失败！',2000);
     }
}
// 根据返回索引判断 图片宽高归属
function widthinit(ite,index){
    if(ite[0].picMsg != null){
        bwidthheight={'picWidth':JSON.parse(ite[0].picMsg).picWidth,'picHeight':JSON.parse(ite[0].picMsg).picHeight};
        paramspicmsg (ite,index)  
        }else{
       bwidthheight={'picWidth':'','picHeight':''};
       paramspicmsg (ite,index)
        } 
}
function paramspicmsg (ite,indexs){
    if(indexs == 0){
        $("#myImgone").attr('src',$(ite)[0].modelUrl);
        if(mbId){
            params1.picMsg = JSON.stringify(bwidthheight);
        }else{
            params1.picMsg = JSON.stringify(widthheight);
        }
        params1.modelId=$(ite)[0].modelId ;
        spcialLinkConfit.specialLinkArr[0].specialInd = ite[0].placeType;
        spcialLinkConfit.specialLinkArr[0].specialContent =ite[0].placeContent;
        spcialLinkConfit.specialLinkArr[0].detailContent =ite[0].detailContent;       
        }else{
         params2.modelId=$(ite)[0].modelId ;
        $("#myImgtwo").attr('src',$(ite)[0].modelUrl);
        if(mbId){
            params2.picMsg = JSON.stringify(bwidthheight);
        }else{
            params2.picMsg = JSON.stringify(widthheight);
        }
        spcialLinkConfit.specialLinkArr[1].specialInd = ite[0].placeType;
        spcialLinkConfit.specialLinkArr[1].specialContent =ite[0].placeContent;
        spcialLinkConfit.specialLinkArr[1].detailContent =ite[0].detailContent;
        }
}
console.log('这是一个下载模板入参')
console.log(modelIdeveyList)
    var formData = new FormData();
    // 提交上传图片
    function getupfilerul(can,e,num){
        var formData = new FormData();
        formData.append('file',$(can)[0].files[0]);
        $.ajax({
            url: root.inter.imgUpload,
            cache: false,  //禁用缓存
            type: "POST",
            // 告诉jQuery不要去处理发送的数据
            processData : false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType : false,
            data: formData,
            success: function (data) {
                for(var i=0; i<data.length; i++){
                    $(can).parent().parent().parent().find('img').removeClass('hide')
                    $(can).parent().parent().parent().find('img').attr("src", data[0].fullPath);
                        $(can).parent().find('.fileupone').html('更换图片');
                        widthheight={'picWidth':width,'picHeight':height};
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        $("#fileUptwo").attr('type','text');
                        $("#fileUptwo").attr('type','file');
                        if(num == 1){
                            params1.picMsg = JSON.stringify(widthheight);
                        }else{
                            params2.picMsg = JSON.stringify(widthheight);
                        }
                }
                if(num  == 1){
                    params1.modelUrl = data[0].fullPath;
                }else{
                    params2.modelUrl = data[0].fullPath;
                }
            }
        })
    }
    // 上传图片返现
    function putDataToPage(e,can,num) {
        //验证
        verificationPicFileType(can)
        verificationPicFileSize(can)
        for(var i = 0; i < e.target.files.length; i++) {
            var file = e.target.files.item(i);
            if(!(/^image\/.*$/i.test(file.type))) {
                continue; //不是图片 就跳出这一次循环
            }
            //实例化FileReader API
            var freader = new FileReader();
            freader.readAsDataURL(file);
            freader.onload = function (e) {
                var data = e.target.result;
                //加载图片获取图片真实宽度和高度
                var img = new Image();
                img.src= data;
                img.onload = function(){
                     width = img.width;
                     height = img.height;
                    if (width != 344 || height != 528 ){
                        $.Huimodalalert('图片尺寸限制为：344*528',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        $("#fileUptwo").attr('type','text');
                        $("#fileUptwo").attr('type','file');
                        return ;
                    }else {
                        getupfilerul(can,e,num)
                    }
                };
            }
        }
        formData.append('file', $(can)[0].files[0]);
    }
      // 图片类型验证
      function verificationPicFileType(file) {
        var flag=false;
        var fileTypes = [".jpg", ".png",".jpeg",".gif"];
        var filePath = file.value;
        //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
        if(filePath){
            var isNext = false;
            var fileEnd = filePath.substring(filePath.indexOf("."));
            isNext = fileTypes.includes(fileEnd.toLowerCase());// 不区分图片后缀大小写格式
            for (var i = 0; i < fileTypes.length; i++) {
                if (fileTypes[i] == fileEnd) {
                    isNext = true;
                    flag= true;
                    break;
                }
            }
            if (!isNext){
                $.Huimodalalert('图片格式支持jpg、jpeg、png、gif',2000);
                file.value = "";
                flag=false;
            }
        }
        return flag;
    }
    //图片大小验证
    function verificationPicFileSize(file) {
        var flag=false;
        var fileSize = 0;
        var fileMaxSize =300;
        var filePath = file.value;
        if(filePath){
            fileSize =file.files[0].size;
            var size = fileMaxSize*Number(1024);
            if (fileSize > size) {
                $.Huimodalalert('图片大小限制不能超过300KB',2000);
                file.value = "";
                flag=false;
            }else{
                flag=true;
            }
        }
        return flag;
    }
    //删除图片
function deletfilefn(e,num){
    if(num == 1){
        $("#myImgone").attr('src','');
    }else{
        $("#myImgtwo").attr('src','');
    }
    $(e).parent().parent().parent().find('img').attr('src','')
    $(e).parent().find('.fileupone').html('图片上传')
    $("#fileUpone").attr('type','text');
    $("#fileUpone").attr('type','file');
    $("#fileUptwo").attr('type','text');
    $("#fileUptwo").attr('type','file');
}
//保存
var dataurl ='';
function savefn(){
    if(mbId){
        dataurl = root.special.updateModel;
    }else{
        dataurl = root.special.addAppModel
    }
    params1.modelUrl =$("#myImgone").attr('src');
    params1.modelStatus=$(".radionamebox").find('input:checked').val();
    params1.modelSpace=$(".radioretivalbox").find('input:checked').val();
    params1.placeType=parseInt(spcialLinkConfit.specialLinkArr[0].specialInd);
    params1.placeContent=spcialLinkConfit.specialLinkArr[0].specialContent;
    params1.detailContent =spcialLinkConfit.specialLinkArr[0].detailContent;


    params2.modelUrl =$("#myImgtwo").attr('src');
    params2.modelStatus=$(".radionamebox").find('input:checked').val();
    params2.modelSpace=$(".radioretivalbox").find('input:checked').val();
    params2.placeType=parseInt(spcialLinkConfit.specialLinkArr[1].specialInd);
    params2.placeContent=spcialLinkConfit.specialLinkArr[1].specialContent;
    params2.detailContent =spcialLinkConfit.specialLinkArr[1].detailContent;

    seavedata= seavedatatone.concat(seavedatatwo);

    var placeType1 = spcialLinkConfit.specialLinkArr[0].specialInd;
    var placeContent1 = spcialLinkConfit.specialLinkArr[0].specialContent;
    var detailContent1 = spcialLinkConfit.specialLinkArr[0].detailContent;
    var modelUrl1 = $("#myImgone").attr('src');

    var placeType2 = spcialLinkConfit.specialLinkArr[1].specialInd;
    var placeContent2 = spcialLinkConfit.specialLinkArr[1].specialContent;
    var detailContent2 = spcialLinkConfit.specialLinkArr[1].detailContent;
    var modelUrl2 = $("#myImgtwo").attr('src')

    var newAry = [
        {id:placeType1,url:modelUrl1,content:placeContent1,detailContent:detailContent1},
        {id:placeType2,url:modelUrl2,content:placeContent2,detailContent:detailContent2}
    ];


/*

    if( spcialLinkConfit.specialLinkArr[0].specialInd == 8 &&  spcialLinkConfit.specialLinkArr[1].specialInd == 8){//无跳转
        if($("#myImgone").attr('src') == '' || $("#myImgtwo").attr('src') == '' ||spcialLinkConfit.specialLinkArr[0].specialInd =='' || spcialLinkConfit.specialLinkArr[1].specialInd =='' ){
            $.Huimodalalert('请填写必填项信息',2000);
         return
        }
    }else if(spcialLinkConfit.specialLinkArr[0].specialInd == -1 || spcialLinkConfit.specialLinkArr[1].specialInd == -1){
        if($("#myImgone").attr('src') == '' || $("#myImgtwo").attr('src') == '' ){
            $.Huimodalalert('请填写必填项信息',2000);
         return
        }else{
            $.Huimodalalert('请填写必填项信息',2000);
            return 
        }
    }else if(spcialLinkConfit.specialLinkArr[0].specialInd == 8 && spcialLinkConfit.specialLinkArr[1].specialInd != 8 ){
        if($("#myImgone").attr('src') == '' || $("#myImgtwo").attr('src') == '' || $("#myImgthree").attr('src') == '' ||  spcialLinkConfit.specialLinkArr[1].specialContent =='' ){
            $.Huimodalalert('请填写必填项信息',2000);
          return
        }
    }else if(spcialLinkConfit.specialLinkArr[1].specialInd == 8 && spcialLinkConfit.specialLinkArr[0].specialInd != 8 ){
        if($("#myImgone").attr('src') == '' || $("#myImgtwo").attr('src') == '' || $("#myImgthree").attr('src') == '' || spcialLinkConfit.specialLinkArr[0].specialInd =='' ||  spcialLinkConfit.specialLinkArr[0].specialContent =='' ){
            $.Huimodalalert('请填写必填项信息',2000);
          return
        }
    }else if( (spcialLinkConfit.specialLinkArr[0].specialContent =='' &&  spcialLinkConfit.specialLinkArr[0].detailContent !='') ){
        if(spcialLinkConfit.specialLinkArr[0].specialInd == 1){
            $.Huimodalalert('暂无该专题，请重新输入',2000);
            return 
        }else if(spcialLinkConfit.specialLinkArr[0].specialInd == 3){
            $.Huimodalalert('暂无该品牌信息，请重新输入',2000);
            return
        }
        
        
    }else if( (spcialLinkConfit.specialLinkArr[1].specialContent =='' &&  spcialLinkConfit.specialLinkArr[1].detailContent !='')){
        if(spcialLinkConfit.specialLinkArr[1].specialInd == 1){
            $.Huimodalalert('暂无该专题，请重新输入',2000);
            return 
        }else if(spcialLinkConfit.specialLinkArr[1].specialInd == 3){
            $.Huimodalalert('暂无该品牌信息，请重新输入',2000);
            return
        }
    }else{
        if($("#myImgone").attr('src') == '' || $("#myImgtwo").attr('src') == '' ||  spcialLinkConfit.specialLinkArr[0].specialInd =='' || spcialLinkConfit.specialLinkArr[0].specialContent ==''|| spcialLinkConfit.specialLinkArr[1].specialInd =='' || spcialLinkConfit.specialLinkArr[1].specialContent ==''){
        $.Huimodalalert('请填写必填项信息',2000);
     return
    }
    }*/
    if(spcialLinkConfit.conditionJudge(newAry)){
        $.ajax({
            url:dataurl,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            contentType: "application/json",
            data:JSON.stringify(seavedata)  ,
            success: function (data) {
                if(data.errorCode == 0){
                    if(mbId){
                        parent.specialEdit.singleModuleDagaGet(mbId,pos)
                    }else{
                        parent.specialEdit.singleModuleDagaGet(data.data,pos)
                    }
                    layer.msg("保存成功",{icon: 6,time:1000},function () {
                        setTimeout(function () {
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        })
                    });
                }else{
                    $.Huimodalalert(data.msg,2000);
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }

}
    function closefn(){
    var curInd = layer.confirm(
    '<span>确认取消已编辑的模块</span>'+'<br/>', {title:'提示',btn: ['确定', '取消']},
     function(index){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
        layer.close(curInd);
    },function(){
        layer.close(curInd);
    });
}
//调用落地页位置
specialInd = 0;
specialContent="";
    $('#specialLink').on('change',function(){
        specialInd = $(this).val();
        if(specialInd !=7 && specialInd !=-1){           
            $('#specContent').load('../../../html/operate/special/special_link.html');
        }else{
            $('#specContent').html('');
        }
    })
